<script lang="ts" setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import jyglService from '@/api/jygl'
import xtpzService from '@/api/xtpz'
import wsjzglService from '@/api/wsjzgl'
import yspglService from '@/api/yspgl'
import { formItems } from '@/views/cxtj/dacx/form-item'
import { SsdaListQueryParam, SpdaListQueryParam } from '@/api/jygl-dto'
import formBox from '@/components/queryTable/form/index.vue'
import tableBox from '@/components/queryTable/table/index.vue'
import detailItem from '@/views/gdgl/jcgsh/component/gdzl/ajwjgl/components/detail-item.vue'
import { TableItem } from '@/api/common'
import TreeUtilDTO from '@/utils/tree'

// 入参
const formLabel = ref()
const loading = ref<boolean>(false)
const treeGjzValue = ref()
const treeRef = ref()
const emit = defineEmits(['addDa'])
/**
 * 数据源
 */
const optionsObjs = ref<any>({})
// 生命周期
onMounted(async () => {
  loading.value = true
  queryDlrsjqx()
  formLabel.value = await formItems('ssflcx')
  loading.value = false
})

const queryDlrsjqx = () => {
  xtpzService.getDlrsjqx({}).then((res: any) => {
    optionsObjs.value.ljdw = TreeUtilDTO.getTreeData(
      (res.data.sqdwxxList || []).map((el: any) => ({
        ...el,
        mc: el.dwmc,
        dm: el.dwbm,
        fdm: el.fdwbm,
      })),
      'dwbm',
      'fdwbm',
    )
  })
}

const total = ref<number>(0)
const page = computed(() => {
  return {
    pageNum: form.value.pageNum,
    pageSize: form.value.pageSize,
    total: total.value,
  }
})
// 查询条件
// 诉讼档案查询条件
const ssFilter = ref({
  ajmc: '',
  ay: [],
  bgqx: '',
  bmsah: '',
  dh: '',
  dsr: '',
  gdnd: '',
  gjz: '',
  jcg: '',
  ljdw: [],
  mj: '',
  cxlx: '2',
})
// 视频档案查询条件
const spFilter = ref({
  bgqx: '',
  dh: '',
  gdnd: '',
  gjz: '',
  ljdw: [],
  lzz: '',
  mj: '',
  splx: '',
  tm: '',
  cxlx: '2',
})
const form = ref({
  pageSize: 20,
  pageNum: 1,
  filter: ssFilter.value as SpdaListQueryParam | SsdaListQueryParam,
})
/*
 * 分页
 */
const changePageNum = (val: number) => {
  form.value.pageNum = val
  getTableData()
}

/*
 * 分页
 */
const changePageSize = (val: number) => {
  form.value.pageNum = 1
  form.value.pageSize = val
  getTableData()
}

const fldm = ref(1)
const getTableData = () => {
  const params = form.value
  loading.value = true
  tableData.value.data = []
  sswjList.value = []
  videoSrc.value = ''
  let queryFn = null
  switch (fldm.value) {
    case 1:
      queryFn = jyglService.querySsdaList
      break
    case 31:
      queryFn = jyglService.querySpdaList
      break
  }
  queryFn &&
    queryFn(params)
      .then((res) => {
        if (res) {
          tableData.value.data = res.data.list
          total.value = res.data.total
          dawsTree.value = undefined
        }
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
      .finally(() => {
        loading.value = false
      })
}
/*
 * 查询按钮
 */
const searchTable = (data: any) => {
  const newObj: any = {}
  for (const key in data) {
    if (key.endsWith('-rq')) {
      const kssj = key.replace('-rq', 'ksrq')
      const jssj = key.replace('-rq', 'jsrq')
      if (data[key]?.length) {
        newObj[kssj] = data[key][0]
        newObj[jssj] = data[key][1]
      } else {
        newObj[kssj] = ''
        newObj[jssj] = ''
      }
    }
    newObj[key] = data[key]
  }
  form.value.filter = newObj
  getTableData()
}

/*
 * 获取表格数据
 */
const tableBoxRef = ref<InstanceType<typeof tableBox>>()
// 诉讼档案表头
const sstitles = ref([
  {
    label: '档号',
    prop: 'dh',
    width: 200,
    custom: false,
    sort: true,
    dqfs: 'left',
  },
  { label: '立卷单位', prop: 'bmmc', width: 120, dqfs: 'left' },
  { label: '归档年度', prop: 'gdnd', width: 120, dqfs: 'left' },
  { label: '保管期限', prop: 'bgqx', width: 120, dqfs: 'left' },
  { label: '密级', prop: 'mj', width: 100, dqfs: 'left' },
  { label: '案件名称', prop: 'ajmc', width: 120, dqfs: 'left' },
  { label: '部门受案号', prop: 'bmsah', width: 200, dqfs: 'left' },
  { label: '检察官', prop: 'jcg', width: 120, dqfs: 'left' },
  { label: '当事人', prop: 'dsr', width: 120, dqfs: 'left' },
  { label: '案由', prop: 'ay', width: 160, dqfs: 'left' },
])
// 视频档案表头
const sptitles = ref([
  {
    label: '档号',
    prop: 'dh',
    width: 200,
    custom: false,
    sort: true,
    dqfs: 'left',
  },
  { label: '立卷单位', prop: 'bmmc', width: 120, dqfs: 'left' },
  { label: '归档年度', prop: 'gdnd', width: 120, dqfs: 'left' },
  { label: '保管期限', prop: 'bgqx', width: 120, dqfs: 'left' },
  { label: '密级', prop: 'mj', width: 120, dqfs: 'left' },
  { label: '题名', prop: 'tm', width: 120, dqfs: 'left' },
  { label: '视频类型', prop: 'splx', width: 120, dqfs: 'left' },
  { label: '录制者', prop: 'lzz', width: 120, dqfs: 'left' },
  {
    label: '录制日期',
    prop: 'lzrq',
    width: 160,
    dqfs: 'left',
    format: 'YYYY-MM-DD',
  },
])
// 表格数据
const tableData = ref<TableItem>({
  data: [],
  titles: sstitles.value,
})

// 左侧分类树
const flTree = ref([
  { mc: '诉讼档案', dm: 1, cj: '1', children: [] },
  { mc: '文书档案', dm: 2, cj: '1', children: [] },
  {
    mc: '音像档案',
    dm: 3,
    cj: '1',
    children: [
      {
        mc: '视频档案',
        dm: 31,
        cj: '2',
      },
      {
        mc: '音频档案',
        dm: 32,
        cj: '2',
      },
      {
        mc: '照片档案',
        dm: 33,
        cj: '2',
      },
    ],
  },
  { mc: '会计档案', dm: 4, children: [], cj: '1' },
  { mc: '其他', dm: 5, children: [], cj: '1' },
])
// 左侧分类树实例
const flTreeRef = ref()
const handleNodeClick = async (node: { mc: string; dm: number }) => {
  fldm.value = node.dm
  if (fldm.value === 1) {
    formLabel.value = await formItems('ssflcx')
    tableData.value.titles = sstitles.value
    form.value.filter = ssFilter.value
  }
  if (fldm.value === 31) {
    formLabel.value = await formItems('spflcx')
    tableData.value.titles = sptitles.value
    form.value.filter = spFilter.value
  }
  getTableData()
}

const leftSmall = ref<boolean>(false)
const middleSmall = ref<boolean>(true)
const rightSmall = ref<boolean>(false)
const dragFlag = ref<boolean>(false)
const moveLenLeft = ref<number>(0)
const moveLenHeight = ref<number>(0)
const moveLenRight = ref<number>(0)
/*
 * 拖拽事件
 */
// 初始距离
// 是否按下
const dragstart = () => {
  dragFlag.value = true
}
/*
 * 左中分屏拖拽
 */
const dragLeft = (e: any) => {
  if (!dragFlag.value || !e.clientX) {
    return
  }
  if (e.clientX && e.clientX - 60 <= 200) {
    moveLenLeft.value = 200
  } else if (e.clientX && e.clientX - 60 >= 300) {
    moveLenLeft.value = 300
  } else {
    moveLenLeft.value = e.clientX - 60
  }
}
/*
 * 上下分屏拖拽
 */
const dragBottom = (e: any) => {
  const screenHeight = JSON.parse(JSON.stringify(screenRef.value.offsetHeight || 0))
  if (!dragFlag.value || !e.clientY) {
    return
  }
  if (e.clientY && screenHeight - e.clientY + 40 <= 270) {
    moveLenHeight.value = 270
  } else if (e.clientY && screenHeight - e.clientY + 40 >= 400) {
    moveLenHeight.value = 400
  } else {
    moveLenHeight.value = screenHeight - e.clientY + 40
  }
}
const dragend = () => {
  dragFlag.value = false
}

/*
 * 右中分屏拖拽
 */
const screenRef = ref<any>()
const dragRight = (e: any) => {
  const screenWidth = JSON.parse(JSON.stringify(screenRef.value.offsetWidth || 0))
  if (!dragFlag.value || !e.clientX) {
    return
  }
  if (screenWidth - e.clientX && screenWidth - e.clientX + 60 <= 500) {
    moveLenRight.value = 500
  } else if (screenWidth - e.clientX && screenWidth - e.clientX + 60 >= 800) {
    moveLenRight.value = 800
  } else {
    moveLenRight.value = screenWidth - e.clientX + 60
  }
}

/*
 * 查询档案条目
 */
const dawsTree = ref<any[]>()
const currentSsda = ref()
const getDatm = (row: any) => {
  if (fldm.value === 31) {
    dawsTree.value = undefined
    middleSmall.value = true
    videoSrc.value = ''
    getYspList(row)
  } else {
    sswjList.value = []
    const params = {
      ajmc: row.ajmc,
      dabh: row.dabh,
    }
    currentSsda.value = row
    jyglService
      .getSsdaws(params)
      .then((res) => {
        const tempList = res.data.filter((el) => el.mc !== '待编目材料')
        dawsTree.value = TreeUtilDTO.getTreeData(tempList || [], 'dm', 'fdm')
        middleSmall.value = false
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  }
}

// 音视频目录列表
const videoSrc = ref('')
const getYspList = (row: any) => {
  const params = {
    dabh: row.dabh,
    mlbh: row.mlbh,
  }
  yspglService
    .getYspmlxx(params)
    .then((res) => {
      videoSrc.value = `${window.IPCONFIG}/fpi/wjfw/download?wjbh=${res.data.wjbh}`
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

// 案卷复卷列表
const sswjList = ref<any[]>([])
const getWjList = (data: any, mlList: any[]) => {
  currentIndex.value = 0
  const params = {
    ajbh: data.wsajbh,
  }
  wsjzglService
    .queryWjList(params)
    .then((res) => {
      const wjListArr: any[] = []
      // 按目录顺序给文件排序
      mlList?.forEach((ml) => {
        res.data.forEach((wj) => {
          if (wj.mlbh === ml.dm) {
            wjListArr.push(wj)
          }
        })
      })
      sswjList.value = wjListArr
      const i = mlList.findIndex((ml) => ml.dm === currentNode.value?.dm)
      if (i === 1) {
        indexChange(mlList[0].sl)
      } else if (i > 1) {
        indexChange(
          mlList.slice(0, i).reduce((pre, next) => {
            return pre + next.sl
          }, 0),
        )
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 点击条目预览
 */
const currentNode = ref<any>()
const previewDa = (data: any) => {
  if (currentNode.value?.dm === data.dm || data.cj === '1') {
    return
  }
  if (data.wsajbh !== currentNode.value?.wsajbh) {
    const ml = TreeUtilDTO.findNode(dawsTree.value || [], data.wsajbh, 'dm')
    getWjList(data, ml?.children)
  } else {
    const params = {
      ajbh: data.wsajbh,
      mlbh: data.dm,
    }
    wsjzglService
      .queryWjList(params)
      .then((res) => {
        nextTick(() => {
          if (res.data.length) {
            const i = sswjList.value.findIndex((wj) => wj.wjbh === res.data[0].wjbh)
            indexChange(i)
          }
        })
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  }
  currentNode.value = data
}

const multipleSelection = ref<any[]>([])
const selectionChange = (val: any[]) => {
  multipleSelection.value = val
}
const ssdaList = ref<any[]>([])
const spdaList = ref<any[]>([])

/*
 * 添加条目关联到借阅单
 */
const addToJyd = () => {
  if (fldm.value === 1) {
    if (checkNodes.value.length) {
      const da = ssdaList.value.find((da) => da.dh === currentSsda.value.dh)
      if (da) {
        da.children = TreeUtilDTO.getTreeData(
          TreeUtilDTO.removeDuplicates(
            [...TreeUtilDTO.flatten(da.children), ...checkNodes.value],
            'dm',
          ).map((el) => ({ ...el, children: null })),
          'dm',
          'fdm',
        )
      } else {
        ssdaList.value.push({
          ...currentSsda.value,
          children: TreeUtilDTO.getTreeData(checkNodes.value, 'dm', 'fdm'),
        })
      }
      ElMessage.success('添加成功')
    } else {
      ElMessage.warning('请至少选择一个目录')
    }
  } else if (fldm.value === 31) {
    spdaList.value = multipleSelection.value
    ElMessage.success('添加成功')
  }
}

const filterNode = (value: any, data: any) => {
  return data.mc.includes(value)
}

/*
 * 勾选诉讼档案目录
 */
const checkNodes = ref<any[]>([])
const check = (data: any, checks: any) => {
  checkNodes.value = [
    ...checks.checkedNodes.map((el: any) => {
      return { ...el, children: [] }
    }),
    ...checks.halfCheckedNodes.map((el: any) => {
      return { ...el, children: [] }
    }),
  ]
  checkNodes.value = checkNodes.value.filter((node) => node.cj !== '1')
}

// 文字过滤
const filterTree = () => {
  treeRef.value?.filter(treeGjzValue.value)
}

/*
 * 打开弹窗
 */
//
const dialogVisible = ref(false)
const openDialog = () => {
  dialogVisible.value = true
  // 分页
  changePageNum(1)
  nextTick(() => {
    flTreeRef.value?.setCurrentKey(1)
  })
}

const closeDialog = () => {
  emit('addDa', ssdaList.value, spdaList.value)
  fldm.value = 1
  dawsTree.value = undefined
  checkNodes.value = []
  multipleSelection.value = []
  ssdaList.value = []
  spdaList.value = []
}

const currentIndex = ref(0)
const indexChange = (index: number) => {
  currentIndex.value = index
}

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择档案"
    width="95%"
    :close-on-click-modal="false"
    @closed="closeDialog"
  >
    <div class="container" ref="screenRef">
      <div
        class="left"
        :class="{ small: leftSmall }"
        :style="{ width: moveLenLeft ? moveLenLeft + 'px' : '' }"
      >
        <div class="left-img" @click="leftSmall = !leftSmall">
          <img src="@/assets/images/zsq.png" alt="" v-if="!leftSmall" />
          <img src="@/assets/images/ysq.png" alt="" v-else-if="leftSmall" />
        </div>
        <el-tree
          ref="flTreeRef"
          :data="flTree"
          :props="{ label: 'mc', children: 'children' }"
          node-key="dm"
          highlight-current
          @node-click="handleNodeClick"
        >
          <template #default="{ data }">
            <span class="custom-tree-node">
              <img v-if="data.cj === '1'" src="/src/assets/images/file-icon.png" alt="" />
              <img v-if="data.cj === '2'" src="/src/assets/images/text-icon.png" alt="" />
              <span>&nbsp;{{ data.mc }}</span>
            </span>
          </template>
        </el-tree>
      </div>
      <!--拖动div-->
      <div
        class="search-drag-box"
        :draggable="true"
        title="可左右拖动"
        @dragstart="dragstart()"
        @dragend="dragend()"
        @drag="dragLeft($event)"
      >
        <div class="dragImg">
          <el-icon class="dargIcon" color="#bdcae2"><MoreFilled /></el-icon>
        </div>
      </div>
      <div class="middle">
        <div
          class="middle-top"
          :style="{ height: moveLenHeight ? `calc(100% - ${moveLenHeight + 12}px)` : '' }"
        >
          <!--表单-->
          <div class="form-box">
            <form-box
              ref="formBoxRef"
              :formLabel="formLabel"
              :formData="form.filter"
              :moreShow="true"
              :optionsObj="optionsObjs"
              @searchEvent="searchTable"
            />
          </div>
          <div class="button-group">
            <div class="button-cart" v-if="fldm === 31">
              <el-button type="primary" @click="addToJyd">添加</el-button>
            </div>
          </div>
          <!--表格-->
          <div
            class="table-box"
            :style="{ height: fldm === 1 ? 'calc(100% - 100px)' : 'calc(100% - 130px)' }"
          >
            <table-box
              :gnbm="fldm === 1 ? 'xzda-ssflcx' : 'xzda-spflcx'"
              ref="tableBoxRef"
              :selectShow="fldm === 31 ? true : false"
              :table-data="tableData"
              :formParams="form"
              :getTableDataParam="page"
              :tableInfo="{ total: page.total }"
              :highlight-current-row="true"
              @changeCurrent="changePageNum"
              @changeSize="changePageSize"
              @selectionChange="selectionChange"
              @rowClick="getDatm"
            >
            </table-box>
          </div>
        </div>
        <!--拖动div-->
        <div
          class="table-drag-box"
          v-if="dawsTree && fldm === 1"
          :draggable="true"
          title="可上下拖动"
          @dragstart="dragstart()"
          @dragend="dragend()"
          @drag="dragBottom($event)"
        >
          <div class="dragImg">
            <el-icon class="dargIcon" color="#bdcae2"><MoreFilled /></el-icon>
          </div>
        </div>
        <div
          v-if="dawsTree && fldm === 1"
          class="middle-bottom"
          :class="{ small: middleSmall }"
          :style="{ height: moveLenHeight ? `${moveLenHeight}px` : '' }"
        >
          <div class="middle-img" @click="middleSmall = !middleSmall">
            <img src="@/assets/images/zsq.png" alt="" v-if="!middleSmall" />
            <img src="@/assets/images/ysq.png" alt="" v-else-if="middleSmall" />
          </div>
          <div class="add-cart">
            <el-button type="primary" @click="addToJyd">添加</el-button>
            <el-input
              v-model="treeGjzValue"
              class="cart-input"
              placeholder="请输入查询关键字"
              @change="filterTree"
            >
              <template #suffix>
                <el-icon @click="filterTree" class="el-input__icon"><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="tree-box">
            <el-tree
              ref="treeRef"
              v-show="!middleSmall"
              :data="dawsTree"
              highlight-current
              :props="{ label: 'mc', children: 'children' }"
              node-key="dm"
              show-checkbox
              :check-strictly="false"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              @check="check"
              @node-click="previewDa"
            >
              <template #default="{ data }">
                <span class="custom-tree-node">
                  <span>{{ data.mc }} ({{ data.sl }})</span>
                </span>
              </template>
            </el-tree>
          </div>
        </div>
      </div>
      <div
        class="search-drag-box"
        :draggable="true"
        title="可左右拖动"
        @dragstart="dragstart()"
        @dragend="dragend()"
        @drag="dragRight($event)"
      >
        <div class="dragImg">
          <el-icon class="dargIcon" color="#bdcae2"><MoreFilled /></el-icon>
        </div>
      </div>
      <div
        class="right"
        :class="{ small: rightSmall }"
        :style="{ width: moveLenRight ? moveLenRight + 'px' : '' }"
      >
        <div class="right-img" @click="rightSmall = !rightSmall">
          <img src="@/assets/images/ysq.png" alt="" v-if="!rightSmall" />
          <img src="@/assets/images/zsq.png" alt="" v-else-if="rightSmall" />
        </div>
        <div class="preview-box">
          <video
            v-if="fldm === 31 && videoSrc"
            :src="videoSrc"
            controls
            controlsList="nodownload"
          ></video>
          <div v-else-if="fldm === 1 && sswjList.length" class="ssda-list">
            <detail-item
              isBm
              :current-index="currentIndex"
              class="detail-wrapper"
              :wjxqxxList="sswjList"
              @indexChange="indexChange"
            ></detail-item>
          </div>
          <el-empty v-else></el-empty>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="default" style="margin-left: 10px" @click="dialogVisible = false"
          >关 闭</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 80vh;
  display: flex;
  justify-content: space-between;

  .left {
    width: 250px;
    height: 100%;
    border: 1px solid #dae4f1;
    position: relative;
    background-color: #fff;
    &.small {
      width: 16px !important;
      border: none !important;
      .el-tree {
        display: none;
      }
    }
    .el-tree {
      :deep(.el-tree-node__content) {
        height: 40px;
      }
    }
  }
  .left > .left-img {
    cursor: pointer;
    position: absolute;
    right: 0;
    top: calc(50% - 27px);
    z-index: 9;
  }
  .middle {
    flex: 1;
    width: calc(100% - 862px);
    height: 100%;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    .middle-top {
      flex: 1;
      height: calc(100% - 284px);
      border: 1px solid #dae4f1;
      width: 100%;
      .form-box {
        width: 100%;
        padding: 10px;
      }
      .table-box {
        padding: 0 10px;
      }
      .container {
        flex-direction: column;
        height: auto;
      }
    }
    .middle-bottom {
      height: 270px;
      border: 1px solid #dae4f1;
      position: relative;
      overflow-y: auto;
      &.small {
        height: 10px !important;
        border: none !important;
      }
      .middle-img {
        z-index: 9;
        cursor: pointer;
        position: absolute;
        left: calc(50% - 4px);
        top: -24px;
        transform: rotate(-90deg);
      }

      .add-cart {
        display: flex;
        justify-content: space-between;
        padding: 10px;

        .cart-input {
          width: 320px;
          .el-input__icon {
            cursor: pointer;
          }
        }
      }
      .tree-box {
        height: calc(100% - 60px);
        overflow: auto;
      }
    }
  }
  .right {
    width: 600px;
    height: 100%;
    border: 1px solid #dae4f1;
    position: relative;
    background-color: #fff;
    &.small {
      width: 16px !important;
      border: none !important;
      .preview-box {
        display: none;
      }
    }
    .preview-box {
      height: 100%;
      overflow-y: auto;
      display: flex;
      justify-content: center;
      video {
        width: 100%;
        padding: 10px;
      }
      .ssda-list {
        height: 100%;
        width: 100%;
        .detail-wrapper {
          width: 100%;
          height: 100%;
          background-color: #fff;
        }
      }
    }
  }
  .right > .right-img {
    position: absolute;
    left: 0;
    top: calc(50% - 27px);
    cursor: pointer;
  }
}

.search-drag-box {
  margin: 0 1px;
  flex-shrink: 0;
  width: 10px;
  height: 100%;
  cursor: col-resize;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;

  .dragImg {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .dargIcon {
      font-size: 29px;
      transform: rotate(90deg);
    }
  }
}
.table-drag-box {
  margin: 1px 0;
  flex-shrink: 0;
  height: 10px;
  width: 100%;
  cursor: row-resize;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;
  .dragImg {
    height: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .dargIcon {
      font-size: 29px;
    }
  }
}

.button-group {
  padding: 0 10px 10px 10px;
  display: flex;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  border-right: none !important;
  color: #0090ff;
  background-color: #d9edff;
}
:deep(.page-export) {
  height: 40px;
  min-height: 32px;
  overflow-x: auto;
}
</style>
